﻿using Learun.Application.Base.AuthorizeModule;
using Learun.Util;
using Learun.Util.Operat;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Learun.Application.Web
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：-框架开发组
    /// 日 期：2017.03.08
    /// 描 述：登录认证（会话验证组件）
    /// </summary>
    public class HandlerApiLoginAttribute : AuthorizeAttribute
    {
        private FilterMode _customMode;

        /// <summary>默认构造</summary>
        /// <param name="Mode">认证模式。force就是需要用户验证，ignore的话不登录也没关系</param>
        public HandlerApiLoginAttribute(FilterMode Mode)
        {
            _customMode = Mode;
        }
        /// <summary>
        /// 响应前执行登录验证,查看当前用户是否有效 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(HttpActionContext filterContext)
        {
            // 登录拦截是否忽略
            if (_customMode == FilterMode.Ignore)
            {
                return;
            }

            //获取token（请求头里面的值）
            var token = HttpContext.Current.Request.Headers["logintoken"] ?? "";
            var loginkey = HttpContext.Current.Request.Headers["loginkey"] ?? "";
            int res = -1;
            //本地登录验证
            res = OperatorHelper.Instance.IsOnLine("", "").stateCode;
            if (res != 1)
            {
                //单点登录验证
                res = OperatorHelper.Instance.IsOnLine(token, loginkey, "", "").stateCode;
            }
            if (res != 1)// 登录过期或者未登录
            {
                HandleUnauthorizedRequest(filterContext);
                return;
            }
        }
        /// <summary>
        /// 这个方法 会在验证失败时调用,可以设定返回状态值和返回信息.
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            base.HandleUnauthorizedRequest(actionContext);
            var response = actionContext.Response = actionContext.Response ?? new System.Net.Http.HttpResponseMessage();
            // 这句话可以改变请求状态值 就是 200 403 之类的那个状态值
            response.StatusCode = System.Net.HttpStatusCode.OK;
            // 将这个出错信息加入到返回对象中.
            var returnContext = new ResParameter { code = ResponseCode.nologin, info = "登录过期或者未登录" }.ToJson();
            response.Content = new StringContent(returnContext);
        }

    }
}